package Servlets;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;


public class DatabaseConnection 
{
	public Statement stmt;
	public ResultSet res;
	public Connection conn;
	
	public DatabaseConnection()
	{
	}
	
	public Connection setConnection()
	{
		try
		{
			//Class.forName("com.mysql.jdbc.Driver");
			Class.forName("com.mysql.jdbc.Driver").newInstance();	
		}														      
		catch (Exception e)
		{
			System.out.println("Unable to load Driver");
			e.printStackTrace();
		}
		try
		{
			conn = null;
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycheckers", "root","root");					
		}													    
		catch (SQLException e)
		{
			System.out.println("Unable to get connection");
			e.printStackTrace();
		}
	
		return conn;
	}
	
	 public void executeQuery(String query, Connection conn)
	{
		 this.conn = conn;
			try 
			{		
				stmt = conn.createStatement();
				stmt.executeUpdate(query);
				/*if(res.next())
				{
					stmt.close();
					conn.close();
				}
				*/
			}
			catch (SQLException e)
			{
					e.printStackTrace();	
			}
			try 
			{
				conn.close();
			} 
			catch (SQLException e) 
			{
					e.printStackTrace();
			}
	}
	
	
    public ResultSet getResult(String query, Connection conn)
	{
		this.conn = conn;
		try 
		{		
			stmt = conn.createStatement();
			stmt.executeUpdate(query);
			/*if(res.next())
			{
				stmt.close();
				conn.close();
			}
			*/
		}
		catch (SQLException e)
		{
				e.printStackTrace();	
		}
		try 
		{
			conn.close();
		} 
		catch (SQLException e) 
		{
				e.printStackTrace();
		}
		return null;
		//return res;
		/*
			this.conn = conn;
			try
			{
				stmt = conn.createStatement();
				res = stmt.executeQuery(query);
			}
			catch (Exception e)
			{
				System.out.println("Unable to execute query");
			}
	

			return res;
			*/
	}
	
}
